package com.fang.async;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextRefreshedEvent;
import org.springframework.stereotype.Component;

//ContextRefreshedEvent 监听整个的容器
@Component
public class QueueListener implements ApplicationListener<ContextRefreshedEvent> {

	private Logger logger = LoggerFactory.getLogger(AsyncController.class);

	@Autowired
	private MockQueue mockQueue;

	@Autowired
	private DeferredResultHolder deferredResultHolder;

	@Override
	public void onApplicationEvent(ContextRefreshedEvent event) {
		// 单线程监听
		new Thread(() -> {
			// 线程2一直监听,并在得到数据之后返回
			while (true) {
				if (StringUtils.isNotBlank(mockQueue.getComplateOrder())) {
					String order = mockQueue.getComplateOrder();
					logger.info("返回订单处理结果，" + order);
					deferredResultHolder.getMap().get(order).setResult("订单完成。。。");
					mockQueue.setComplateOrder(null);
				} else {
					try {
						Thread.sleep(100);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		}).start();

	}
}
